import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import ProfileView from '../views/ProfileView.vue'
import StartPage from '../views/StartPage.vue'
import CategoryView from '../views/CategoryView.vue'
import PostDetailView from '../views/PostDetailView.vue'
import NewPostView from '../views/NewPost.vue'
import LoginView from '../views/LoginView.vue'
import AdminView from '../views/AdminView.vue'
import RegisterView from '../views/RegisterView.vue'
import AuthView from '../views/AuthView.vue'
import MembershipCenterView from '../views/MembershipCenterView.vue'
import MembershipUpgradeView from '../views/MembershipUpgradeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'startpage',
      component: StartPage,
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/category/:categoryId',
      name: 'category',
      component: CategoryView,
      props: true
    },
    {
      path: '/category/:categoryId/posts',
      name: 'categoryPosts',
      component: () => import('../views/CategoryPostsView.vue'),
      props: true
    },
    {
      path: '/post/:postId',
      name: 'postDetail',
      component: PostDetailView,
      props: true
    },
    { path: '/profile', name: 'profile', component: ProfileView, meta: { requiresAuth: true } },
    { path: '/profile/videos', name: 'profileVideos', component: ProfileView, meta: { requiresAuth: true } },
    { path: '/profile/likes', name: 'profileLikes', component: ProfileView, meta: { requiresAuth: true } },
    { path: '/new-post', name: 'newPost', component: NewPostView, meta: { requiresAuth: true } },
    {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  { path: '/admin', name: 'admin', component: AdminView, meta: { requiresAdmin: true } },
    { path: '/register', name: 'register', component: RegisterView },
    { path: '/auth', name: 'auth', component: AuthView },
    // 会员相关路由
    { path: '/membership/center', name: 'membershipCenter', component: MembershipCenterView, meta: { requiresAuth: true } },
    { path: '/membership/upgrade', name: 'membershipUpgrade', component: MembershipUpgradeView, meta: { requiresAuth: true } },
    // 404 页面重定向到主页
    { path: '/:pathMatch(.*)*', redirect: '/home' }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 从本地存储获取用户状态
  const savedState = localStorage.getItem('userState')
  let isLoggedIn = false
  let isAdmin = false
  
  if (savedState) {
    const userState = JSON.parse(savedState)
    isLoggedIn = userState.isLoggedIn
    isAdmin = userState.userInfo?.isAdmin || false
  }
  
  // 标记已访问开始页面
  if (to.name === 'startpage') {
    localStorage.setItem('hasVisitedStartPage', 'true')
  }
  
  // 检查管理员权限
  if (to.meta.requiresAdmin) {
    if (!isLoggedIn) {
      next('/login')
    } else if (!isAdmin) {
      // 非管理员用户重定向到主页
      alert('您没有管理员权限！')
      next('/home')
    } else {
      next()
    }
  }
  // 只对需要登录的页面进行限制
  else if (to.meta.requiresAuth && !isLoggedIn) {
    next('/login')
  } 
  // 如果用户已登录且访问登录/注册页面，则重定向到主页
  else if (isLoggedIn && ['login', 'register', 'auth'].includes(to.name)) {
    next('/home')
  }
  // 如果用户已经访问过开始页面，并且当前在开始页面，则重定向到主页
  else if (localStorage.getItem('hasVisitedStartPage') && to.name === 'startpage' && isLoggedIn) {
    next('/home')
  }
  else {
    next()
  }
})

export default router
